package com.ls.io.rpc.transport;

import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class ClientPool{
    private InetSocketAddress address;
    private int poolSize;
    private int size = 0;
    private BlockingQueue<NioSocketChannel> queue;
    private NioSocketChannel[] channels;

    public ClientPool(InetSocketAddress address, int poolSize) {
        this.address = address;
        this.poolSize = poolSize;
        this.queue = new ArrayBlockingQueue<>(poolSize);

        channels = new NioSocketChannel[poolSize];
        for(int i = 0; i <poolSize; i++){
//            queue.offer(ClientFactory.createClient(address));
            channels[i] = ClientFactory.createClient(address);
        }

    }

//    public NioSocketChannel getClient(){
//        if(queue.isEmpty() && size < poolSize){
//            synchronized (this){
//                if(queue.isEmpty() && size < poolSize){
//                    queue.offer(ClientFactory.createClient(address));
//                    size++;
//                }
//            }
//        }
//
//        try {
//            NioSocketChannel client =  queue.poll(3, TimeUnit.SECONDS);
//
//            return client;
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }

    public NioSocketChannel getClient(){
        int index = 0;
        return channels[index];
    }

    public void back(NioSocketChannel nioSocketChannel){
        queue.offer(nioSocketChannel);
    }


}